import "./indes.scss";
interface IOptions {
  currentIndex: number;
  data: any[];
  callBack?: (newIdx: number) => void;
}
interface IData {
  navItem: string;
  pageItem: string;
}

class PgTab {
  private _curIdx;
  private _data;
  private _callBack;
  private _oNavContainer: HTMLElement | null = null;
  private _oPgContainer: HTMLElement | null = null;
  private _oNavITems: HTMLCollection | null = null;
  private _oPageItems: HTMLCollection | null = null;
  constructor(options: IOptions) {
    this._data = options.data;
    this._curIdx = this._chexkIndex(options.currentIndex);
    this._callBack = options.callBack;
  }
  private _chexkIndex(index: number | undefined): number {
    const _idx = index ? index >>> 0 : 0;
    if (_idx >= this._data.length) {
      return 0;
    }
    return _idx;
  }
  private handleNavclick(e: Event) {
    const tar = e.target as HTMLElement;

    const className = tar.className;
    if (className === "nav-item") {
      this._oNavITems![this._curIdx].className = "nav-item";
      this._oPageItems![this._curIdx].className = "page-item";
      this._curIdx = [].indexOf.call(this._oNavITems, tar as never);

      this._oNavITems![this._curIdx].className += " current";
      this._oPageItems![this._curIdx].className += " current";
      this._callBack && this._callBack(this._curIdx);
    }
  }
  private bindEvent() {
    this._oNavITems = this._oNavContainer!.getElementsByClassName("nav-item");
    this._oPageItems = this._oPgContainer!.getElementsByClassName("page-item");
    this._oNavContainer?.addEventListener(
      "click",
      this.handleNavclick.bind(this)
    );
  }
  render() {
    this._oNavContainer = document.createElement("div");
    this._oPgContainer = document.createElement("div");
    const oWraperContainer: HTMLElement = document.createElement("div");
    this._oNavContainer.className = "pg-nav";
    this._oPgContainer.className = "pg-page";
    oWraperContainer.className = "pg-tab";
    this._data.forEach((it: IData, index: number) => {
      this._oNavContainer!.innerHTML += `
             <div
                class='nav-item${this._curIdx === index ? " current" : ""}' 
                >
                ${it.navItem}
            </div>
        `;
      this._oPgContainer!.innerHTML += `
             <div
                class='page-item${this._curIdx === index ? " current" : ""} ' 
                >
                ${it.pageItem}
            </div>
        `;
    });
    oWraperContainer.appendChild(this._oNavContainer);
    oWraperContainer.appendChild(this._oPgContainer);
    this.bindEvent();
    return oWraperContainer;
  }
}

export default PgTab;
